#!/usr/bin/env python
import sys

primers_test = {'t7all': 'TAATACGACTCACTATAG',
           't73g' : 'TAATACGACTCACTATAGGG',
           'up' : 'CGACGTTGTAAAACGACGGCCAGT',
           'badrev' : 'GATTTAATCTGTATCAGG',
           'rpop' : 'GGAATTGTGAGCGGATTACA',
           'upop' : 'GGTAACGCCAGGGTTTTCC',
           'rp' : 'CAGGAAACAGCTATGACC',
           'pc31rev' : 'TAGAAGGCACAGTCGAGG'}

def read_primers( f='primers_cleaned.csv'):
    lines = open(f).readlines()
    pairs = [ l.split('\t') for l in lines ]
    pairs = [ (n, p.strip().replace('3','')) for n,p in pairs ]
    return dict( pairs )

primers = read_primers()

def reverse( seq ):
    """reverse complement of a nucleotide sequence"""
    d = {'A':'T', 'C':'G', 'T':'A', 'G':'C' }
    
    r = [ d[ x ] for x in seq ]
    r.reverse()
    r = ''.join( r )
    return r

def report( seq, primers):
    
    rv = reverse( seq )
    
    for pname, pseq in primers.items():
        if pseq in seq:
            print '%20s %i matches forward @%i\t%s' % \
                  (pname,seq.count( pseq ), seq.find( pseq ), pseq )
        if pseq in rv:
            print '%20s %i matches reverse @%i\t%s' % \
                  (pname, rv.count( pseq ), len(seq)-rv.find( pseq ), pseq)

def parse( f ):
    p = open( f  ).readlines()
    p = p[1:] ## remove leading line
    p = ''.join( p )
    p = p.replace('\n','').strip().upper()

    return p 

if len( sys.argv ) < 2:
    print \
"""Check plasmid sequence against sequencing primers.
Usage:
    search_primers.py |sequence.fasta|

This is quick and dirty. The primers are read from the file primers.csv
which is expected in the current working folder. primers.csv has been
hand-extracted from the EMBL sequencing facility primers list.

Raik
"""
    sys.exit( 0 )

seq = parse( sys.argv[1] )
print "Primer search against the following primers:\n(%r)" % primers.keys()
print
print "Matching primers:"
report (seq, primers )
